<template>
  <PageLayout>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('Pairing.ScanError.Navigator.FindApplianceVib.Title') }}</view>
      </HeaderLayout>
    </template>
    <view class="scan-error">
      <view class="scan-title">{{ $t('Pairing.ScanError.InPutApplianceVib.Title') }}</view>
      <view class="search-section">
        <!-- 搜索框 -->
        <view class="search-box display-between">
          <view class="search-input-box">
            <input class="search-input" type="text" confirm-type="search" :value="searchValue" @input="editInput" />
            <view class="error-tips" v-if="!isValueError && searchValue != ''">{{
              $t('Pairing.ScanError.InPutText.Tips.Text')
            }}</view>
          </view>
          <view class="submit-btn" @click="submitVib">{{ $t('Pairing.ScanError.Submit.Button.Text') }}</view>
        </view>
        <!-- 模糊搜索结果 -->
        <view class="serach-layer" v-if="searchValue != '' && isValueError">
          <view class="fuzzy-box" v-if="fuzzyVibList.length > 0">
            <view class="layer-box" v-for="(item, index) in fuzzyVibList" :key="index" @click="goPair(item.value)">
              <rich-text :nodes="item.text"></rich-text>
            </view>
          </view>
          <view class="fuzzy-no-content" v-if="fuzzyVibList.length === 0 && isValueError">{{
            $t('Pairing.ScanError.SearchNoResult.Tips.Text')
          }}</view>
        </view>
        <!-- 搜索指南 -->
        <view class="search-guide">
          <view class="guide-title">{{ $t('Pairing.ScanError.ApplianceVibSample.Tips.Text') }}</view>
          <view class="guide-des">{{ $t('Pairing.ScanError.ApplianceENR.Tips.Text') }}</view>
          <image :src="`${baseImgUrl}HC3.0_ENumberLocation.png`" class="guide-img" mode="aspectFit"></image>
        </view>
        <!-- 图片列表 -->
        <view class="img-list" v-show="!searchValue">
          <view class="img-tips"
            >您可以在<text class="height-light">家电说明书</text> 、<text class="height-light">购机发票</text> 或<text
              class="height-light"
              >家电机身</text
            >上找到家电型号。以下是针对家电机身上型号所在位置的指引，以帮助您更方便的找到：</view
          >
          <view class="applianceImgbox">
            <view class="applianceList" v-for="(item, index) in applianceTypeList" :key="index">
              <view class="applianceHeader" @click="changeList(index)">
                <text class="brand-title">{{ item.title }}</text>
                <image
                  mode="aspectFit"
                  class="arrow-right"
                  :class="{ toBottom: item.show, toRight: !item.show }"
                  src="/static/home/MessageCenterArrow.png"
                />
              </view>
              <view v-if="item.show" class="listImg">
                <image :src="`${baseImgUrl}${item.imgUrl}`" mode="aspectFit" class="imgIcon" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </PageLayout>
</template>
<script lang="ts">
export type ApplianceTypeListType = {
  title: string
  imgUrl: string
  show: boolean
}
export type TargetListType = {
  value: string
  text: string
}
export type SearchValueType = {
  value: string
  num: number
}
</script>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'

import { getFuzzySearchData } from '@/api/appliance'
import netconfig from '@/config/netconfig'
import { useI18n } from 'vue-i18n'
import { actionDebounce, redirectTo } from '@/utils/mpHelper'
import { cloneDeep } from 'lodash'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { TrackType, trackEvent } from '@/dataReport/tracks'
const i18n = useI18n()

const headerStyle = {
  backgroundColor: '#fff',
}
const pairingSource = '手动点击'
const baseImgUrl = netconfig.IMGURL + 'WX_HC_Program/Assets/icons/'
const searchValue = ref('')
const isValueError = ref(false)
const fuzzyVibList = ref<TargetListType[]>([])
const applianceTypeList = ref<ApplianceTypeListType[]>([
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuidePLC.Title'),
    imgUrl: 'HC3.0_VIB_Location_LC.jpg',
    show: true,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuidePRF.Title'),
    imgUrl: 'HC3.0_VIB_Location_CL.jpg',
    show: false,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuidePDC.Title'),
    imgUrl: 'HC3.0_VIB_Location_DC.jpg',
    show: false,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuidePCG.Title'),
    imgUrl: 'HC3.0_VIB_Location_CG.jpg',
    show: false,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuideBIWD.Title'),
    imgUrl: 'HC3.0_VIB_Location_BIWD.jpg',
    show: false,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuidePCF.Title'),
    imgUrl: 'HC3.0_VIB_Location_CP.jpg',
    show: false,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuideHood.Title'),
    imgUrl: 'HC3.0_VIB_Location_Hood.jpg',
    show: false,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuideHob.Title'),
    imgUrl: 'HC3.0_VIB_Location_Hob.jpg',
    show: false,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuideWD.Title'),
    imgUrl: 'HC3.0_VIB_Location_MD.jpg',
    show: false,
  },
  {
    title: i18n.t('Pairing.ScanError.ApplianceGuideCookit.Title'),
    imgUrl: 'HC3.0_VIB_Location_Cookit.jpg',
    show: false,
  },
])

/**
 * 编辑输入框
 * @param e
 */
function editInput(e: Event) {
  searchValue.value = (e as unknown as WechatMiniprogram.Input).detail.value
  checkSearchValue(searchValue.value)
  if (isValueError.value) {
    fuzzySearchFun(searchValue.value)
  }
}
/**
 * 校验输入框文本
 */
function checkSearchValue(value: string) {
  const pattern = /^[A-Za-z0-9]+$/
  if (pattern.test(value)) {
    isValueError.value = true
  } else {
    isValueError.value = false
  }
}
/**
 * 模糊搜索接口
 */
async function fuzzySearchFun(key: string) {
  let res: any = null
  try {
    const displayed = netconfig.isTester ? 0 : 1
    res = await getFuzzySearchData(key, displayed)
  } catch (error) {
    res = error
  } finally {
    fuzzyVibList.value = getHighlightRows(res.data, searchValue.value)
  }
}
/**
 * 提交
 */
const submitVib = actionDebounce({
  delay: 3000,
  call: async () => {
    if (fuzzyVibList.value.length === 0) return
    await goPair(fuzzyVibList.value[0].value)
  },
})
// 获取高亮显示数据
function getHighlightRows(sourceList: string[], searchValue: string): TargetListType[] {
  if (searchValue.length === 0) return []
  const searchText = searchValue.toUpperCase()
  const searchList = searchText.split('')
  let newSearchList: SearchValueType[] = []
  searchList.forEach((item) => {
    newSearchList.push({
      value: item,
      num: getKeyWordsNumber(item, searchList),
    })
  })

  return sourceList.reduce((targetList: TargetListType[], sourceItem: string) => {
    let sourceItemText = cloneDeep(sourceItem)
    if (sourceItem === 'MR12010920') {
      sourceItemText = 'MR120'
    } else if (sourceItem === 'MR10010528') {
      sourceItemText = 'MR100'
    } else if (sourceItem === 'MR100iRF10720') {
      sourceItemText = 'MR100iRF'
    } else if (sourceItem === 'MR100iRF10720EMS') {
      sourceItemText = 'MR100iRFEMS'
    }
    let sourceSearchList = cloneDeep(newSearchList)
    const newSourceText = sourceItemText.split('')
    let showText = ''
    newSourceText.forEach((item) => {
      let findIndex = sourceSearchList.findIndex((textItem: SearchValueType) => textItem.value == item.toUpperCase())
      if (findIndex != -1 && sourceSearchList[findIndex].num > 0) {
        sourceSearchList[findIndex].num = sourceSearchList[findIndex].num - 1
        showText += `<span style='color: #408df2;'>${item}</span>`
      } else {
        showText += `<span>${item}</span>`
      }
    })
    targetList.push({
      value: sourceItemText,
      text: showText,
    })
    return targetList
  }, [])
}
/**
 * 获取字符串在数组中的个数
 * @param {*} params
 */
function getKeyWordsNumber(keywords: string, list: string[]) {
  let allNumber = 0
  list.forEach((item) => {
    if (item === keywords) {
      allNumber++
    }
  })
  return allNumber
}
/**
 * 跳转配对页面
 */
function goPair(choosenVib: string) {
  safeTrack(() => {
    let trackData = {
      search_words: searchValue.value,
      appliance_vib: choosenVib,
    }
    trackEvent('search_vib', trackData, TrackType.BusinesssScene)
  })
  let vib = choosenVib
  if (choosenVib === 'MR120') {
    vib = 'MR12010920'
  } else if (choosenVib === 'MR100') {
    vib = 'MR10010528'
  } else if (choosenVib === 'MR100iRF') {
    vib = 'MR100iRF10720'
  } else if (choosenVib === 'MR100iRFEMS') {
    vib = 'MR100iRF10720EMS'
  }

  return redirectTo('/pages/pairing/confirmAppliance/index', {
    vib,
    pairingSource,
  })
}
/**
 * 展开列表
 * @param index
 */
function changeList(index: number) {
  applianceTypeList.value[index].show = !applianceTypeList.value[index].show
}
</script>
<style lang="less">
.scan-error {
  font-family: 'PingFang SC';
  font-style: normal;
  padding: 0 32rpx;
  overflow: hidden;
  position: relative;
  height: 100%;
  overflow-y: auto;
  .display-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .scan-title {
    font-weight: 600;
    font-size: 64rpx;
    line-height: 90rpx;
    color: var(--dark-color);
  }
  .search-section {
    margin-top: 30rpx;
    .search-box {
      margin-top: 70rpx;
      .search-input-box {
        position: relative;
        .search-input {
          width: 510rpx;
          height: 88rpx;
          line-height: 88rpx;
          padding-left: 20rpx;
          border: 1px solid #b4b9c3;
          box-sizing: border-box;
        }
        .error-tips {
          color: red;
          font-size: 24rpx;
          position: absolute;
          left: 0;
          top: 90rpx;
        }
        .clear-img-box {
          width: 88rpx;
          height: 88rpx;
          position: absolute;
          right: 0rpx;
          top: 0rpx;
          z-index: 9;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: yellow;
          .clear-icon {
            width: 30rpx;
            height: 30rpx;
            border-radius: 50%;
          }
        }
      }

      .submit-btn {
        width: 124rpx;
        height: 88rpx;
        line-height: 88rpx;
        text-align: center;
        background-color: var(--dark-color);
        color: #fff;
        margin-left: 34rpx;
      }
    }
  }
  .serach-layer {
    width: 716rpx;
    background-color: #fff;
    position: absolute;
    top: 280rpx;
    z-index: 5;
    height: calc(100vh - 360rpx);
    overflow: auto;
    .fuzzy-box {
      position: relative;
      width: 100%;
      height: 100vh;
      .layer-box {
        color: rgba(45, 55, 70, 1);
        line-height: 80rpx;
        text-align: left;
        border-bottom: 1px solid #e9e9ed;
        .fuzzyHighlight {
          color: #408df2;
        }
      }
    }
    .fuzzy-no-content {
      width: 100%;
      height: 100vh;
      color: rgba(var(--dark-vector), 0.6);
      font-size: 28rpx;
      font-weight: 400;
      line-height: 40rpx;
    }
  }
  .search-guide {
    height: 234rpx;
    background-color: #e9e9ed;
    padding: 24rpx;
    margin-top: 40rpx;
    box-sizing: border-box;
    .guide-title {
      font-weight: 500;
      font-size: 28rpx;
      line-height: 40rpx;
      color: var(--dark-color);
    }
    .guide-des {
      font-weight: 400;
      font-size: 24rpx;
      line-height: 40rpx;
      color: var(--dark-color);
    }
    .guide-img {
      height: 102rpx;
      border-radius: 8rpx;
      margin-top: 6rpx;
    }
  }
  .img-list {
    margin: 8rpx 0 8rpx;
    .img-tips {
      font-weight: 500;
      font-size: 32rpx;
      line-height: 40rpx;
      color: rgba(64, 141, 242, 1);
      font-weight: 400;
      padding-bottom: 16rpx;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        display: block;
        width: 100vw;
        height: 1px;
        bottom: 0;
        left: -32rpx;
        background-color: rgba(233, 233, 237, 1);
      }
      .height-light {
        color: var(--primary-blue-medium, #408df2);
        font-weight: 500;
      }
    }
    .uni-section .uni-section-header {
      padding: 0;
    }
    .type-title {
      width: 100%;
    }
    .type-text {
      color: var(--primary-petrol, #2d3746);
      font-size: 34rpx;
      padding: 0 30rpx;
      font-weight: 400;
      height: 88rpx;
      display: flex;
      align-items: center;
      border-bottom: rgba(233, 233, 237, 1);
      opacity: 0.6000000238418579;
    }
  }
}
.applianceImgbox {
  .applianceHeader {
    height: 112rpx;
    border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
  }

  .arrow-right {
    width: 49rpx;
    height: 48rpx;
  }

  .toBottom {
    transform: rotate(90deg);
    transition: all 0.3s;
  }
  .toRight {
    transform: rotate(0deg);
    transition: all 0.3s;
  }

  .brand-title {
    font-weight: 500;
    font-size: 17px;
    line-height: 48rpx;
    color: #333333;
    opacity: 0.9;
  }
}
</style>
